Skip to content

fix(storage): close worker loop async clients - #4740

Closed
be-student wants to merge 2 commits into
volcengine:mainfrom
be-student:codex/fix-4726-loop-client-shutdown
Closed

be-student wants to merge 2 commits into
volcengine:mainfrom
be-student:codex/fix-4726-loop-client-shutdown

Conversation

@be-student

Copy link
Copy Markdown

Description

Queue workers previously closed their private event loop while LoopScopedAsyncClientCache instances still retained clients created on that loop. Later garbage collection could attempt to close an OpenAI/httpx transport against the dead loop and raise RuntimeError: Event loop is closed in unrelated work.

This change registers loop-scoped caches weakly and closes only the clients owned by the current worker loop before loop.close(). Clients belonging to other active loops remain available.

Human Involvement

  • A human participated in the implementation or review loop
  • This PR was generated entirely by AI agents without human participation in the loop

Related Issue

Fixes #4726

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)
  • Performance improvement
  • Test update

Changes Made

  • Track live LoopScopedAsyncClientCache instances with weak references.
  • Add current-loop cleanup that prefers aclose() and falls back to close().
  • Run that cleanup on each queue worker before closing its event loop.
  • Cover loop isolation and the real queue-worker shutdown path.

Testing

  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • I have tested this on the following platforms:
    • Linux
    • macOS
    • Windows

Commands:

PYTHONPATH=$PWD /Users/song-eun-u/Documents/github/oss-contributions/OpenViking/.venv/bin/python -m pytest -q --no-cov tests/unit/test_async_client_cache.py tests/storage/test_queue_manager.py
/Users/song-eun-u/Documents/github/oss-contributions/OpenViking/.venv/bin/ruff check openviking/utils/async_client_cache.py openviking/storage/queuefs/queue_manager.py tests/unit/test_async_client_cache.py tests/storage/test_queue_manager.py
/Users/song-eun-u/Documents/github/oss-contributions/OpenViking/.venv/bin/ruff format --check openviking/utils/async_client_cache.py openviking/storage/queuefs/queue_manager.py tests/unit/test_async_client_cache.py tests/storage/test_queue_manager.py
PYTHONPATH=$PWD /Users/song-eun-u/Documents/github/oss-contributions/OpenViking/.venv/bin/mypy openviking/utils/async_client_cache.py openviking/storage/queuefs/queue_manager.py

Result: 6 focused tests passed; Ruff and mypy passed. The first uv run pytest attempt could not build the editable package because Cargo was unavailable locally, so the focused checks used the existing project virtual environment with the worktree on PYTHONPATH.

Checklist

  • My code follows the project's coding style
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

Screenshots (if applicable)

Not applicable.

Additional Notes

The change affects only internal client lifecycle behavior. It does not alter public APIs, configuration, or persisted data.

@now-ing

now-ing commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Review: fix(storage): close worker loop async clients

Reviewed against the #4726 analysis — this addresses the worker-loop leg of that failure mode cleanly, and the classmethod shape makes it reusable for other loop owners.

What checks out

  • The WeakSet of cache instances + close_current_loop_clients() popping every cache's client for the current loop is the right granularity: it closes embedder, VLM, and any future cache's clients built on that loop in one call, without touching clients owned by other loops. pop_for_loop under the per-cache lock and the WeakKeyDictionary keying (entries vanish with the loop object) both hold up.
  • Calling it via loop.run_until_complete(...) in the worker's finally before loop.close() — and after asyncio.set_event_loop(None) — matches the constraint that transports must be closed on the loop that owns them. Re-entering run_until_complete on a stopped-but-not-closed loop after a prior worker exception is legal here, and the except Exception guard keeps a failed close from eating the original shutdown path.
  • _close_async_client preferring aclose with a sync close fallback, and the dedup-by-id in _close_clients, avoid double-close hazards.
  • Once these clients are properly closed, their later __del__ no longer schedules aclose on whatever loop is running — so even the still-reachable survivors (see below) stop producing RuntimeError: Event loop is closed.

Scope note (complementary, not blocking)

#4726 traced two more reference legs that this PR intentionally doesn't touch: viking_fs._instance is never cleared after init_viking_fs, and OpenVikingService.close() closes the embedder's cache but not the VLM's. With the worker-loop clients now closed those references stop being error-producing, but in embeddings that re-initialize OpenViking per test (the reporter's setup), clients built on each service's own loop can still leak through those singletons until GC. The classmethod added here (close_current_loop_clients) is exactly the primitive a follow-up can call from OpenVikingService.close()/init_viking_fs teardown to close that leg — worth a tracking comment on #4726 so the remaining scope is explicit.

Tests: the worker-loop integration test (events ordering: close before loop close) and the classmethod unit tests cover the new path; LGTM.

@now-ing

now-ing commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Verified this end-to-end on top of the PR head (7ff4474) — the mechanism is sound and the tests have real discriminative power. Detailed evidence below.

1. The core mechanism, confirmed against openai itself

The fix works because AsyncHttpxClientWrapper.__del__ (openai _base_client.py:1515) short-circuits on if self.is_closed: return. I probed the exact lifecycle from the issue with a real AsyncOpenAI client:

  • Without the fix (worker loop builds a client, loop.close(), then GC fires while a different loop is running): __del__ calls asyncio.get_running_loop().create_task(self.aclose()) on the foreign loop — confirmed: an aclose() task is scheduled there. That's the issue's failure mode (with live pooled connections the transport close then raises RuntimeError: Event loop is closed in unrelated code).
  • With the fix: close_current_loop_clients() awaits aclose() to completion while the worker loop is still alive → http.is_closed is True → the same __del__ is a no-op, zero tasks scheduled on the foreign loop.

So the PR defuses the symptom at exactly the right point, even though the retaining references from the issue (viking_fs._instance, VLMConfig._vlm_instance) are left untouched — by design, and correctly scoped: closing the clients before their loop dies makes those references harmless.

2. Tests are discriminative (mutation-tested)

  • Mutation A — revert _queue_worker_loop's finally to a bare loop.close() (drop the shutdown call): test_queue_worker_closes_loop_scoped_clients_before_its_loop fails precisely, the other tests in the file stay green.
  • Mutation B — make pop_for_loop return all cached clients (over-close, breaking cross-loop isolation): test_close_current_loop_clients_closes_only_clients_owned_by_that_loop fails precisely on the cache.has_clients() retained-loop assertion.

Both tests guard the exact property they claim to guard. Full suite locally: 6/6 in the two touched files green; broader regression over cache consumers (test_openai_embedder_http_pool, test_cohere_embedder) green; test_local_embedder has 1 failure that reproduces identically on clean upstream/main → environment-related, not from this PR.

3. Design checks

  • Weak registration: _instances WeakSet + snapshot-under-lock before iteration avoids both leaks and RuntimeError: Set changed size during iteration; each instance's pop_for_loop takes the existing per-instance _lock, so a concurrent get() on another loop is safe.
  • Cross-loop isolation is load-bearing and correct: only the dying loop's client is popped/closed; clients on live loops stay cached. This matters because the same cache instance is shared by the worker and the server loop in the same process.
  • asyncio.set_event_loop(None) before loop.close() is a nice extra — prevents a pooled worker thread from inheriting a dead loop via the thread-local policy.
  • Scope is right: _execute_rollout_request_in_thread (dataset_service.py:476) is the only other self-managed loop, and it deliberately keeps its loop alive across requests (its comment names this exact RuntimeError) — so the queue worker is the only place that closes a private loop with clients attached, and hooking only queue_manager is the correct scope, not an oversight.

4. Minor notes (all non-blocking)

  1. _fallback_client is not covered by pop_for_loop — clients created via get() from a no-running-loop context would survive close_current_loop_clients(). In practice the worker always runs inside its loop so this path can't trigger there, but it may be worth a one-line docstring note on close_current_loop_clients ("per-loop entries only; the no-loop fallback client is managed by close_all*").
  2. The happy-path test drives the worker via a normal stop_event; the except Exception recovery path inside the worker also lands in the same finally, so coverage there is inherited — fine as is, just noting it.
  3. Heads-up: both CI workflows are sitting in action_required on my read — the fork workflows need approval to run, so there's no CI signal yet for this change.

Nice fix — the WeakSet registration neatly extends shutdown to the VLM/embedder caches (which have no close_all* callers today) without touching their call sites. LGTM with the notes above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

3 participants